import React, { Component } from 'react'
import { Table, Space, Image, Button, Input, Modal, Descriptions, Badge, Spin, message, Tag, Popconfirm,notification } from 'antd'
import { requestOrderList, requestModifiedOrderToSend, requestModifiedNoStoreOrder } from '../../api/order'
import { requestShopDetail } from '../../api/shop'
import { SearchOutlined } from '@ant-design/icons'
import * as PropTypes from 'prop-types'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'

function Highlighter (props) {
    return null
}

Highlighter.propTypes = {
    highlightStyle: PropTypes.shape({ padding: PropTypes.number, backgroundColor: PropTypes.string }),
    textToHighlight: PropTypes.any,
    autoEscape: PropTypes.bool,
    searchWords: PropTypes.arrayOf(PropTypes.any)
}

export class Order extends Component {
    state = {
        dataSource: [],
        shopDetail: {},
        tableHeight: window.innerHeight - 300,
        loading: true,
        loadingDetail: true,
        shopDetailVisible: false,
        show:true
    }

    componentDidMount () {
        if(!localStorage.getItem('orderNotify')){
            const key=`open${Date.now()}`
            notification.info({
                message: '使用提示',
                description: '点击表头放大镜图标可以进行订单查询，支持模糊查询',
                duration: null,
                // eslint-disable-next-line
                btn:<a onClick={() => {
                    notification.close(key)
                    localStorage.setItem('orderNotify',true)
                }}>不再提示</a>,
                key
            })
        }
        this.init()
    }

    init () {
        requestOrderList().then(res => {
            this.setState({
                dataSource: res.data,
                loading: false
            })
        })
    }

    getColumnSearchProps = (dataIndex, placeholder, extra = '_id') => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={node => {
                        this.searchInput = node
                    }}
                    placeholder={placeholder ? placeholder : `Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ marginBottom: 8, display: 'block' }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined/>}
                        size="small"
                    >
                        搜索
                    </Button>
                    <Button onClick={() => this.handleReset(clearFilters, confirm)} size="small">
                        重置
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }}/>,
        onFilter: (value, record) =>
            record[dataIndex]
                ? record[dataIndex].toString().toLowerCase().includes(value.replace(/\s/g,"").toLowerCase()) || (record[extra] && record[extra].toString().includes(value.replace(/\s/g,"")))
                : '',
        onFilterDropdownVisibleChange: visible => {
            if (visible) {
                setTimeout(() => this.searchInput.select(), 100)
            } else {
                this.setState({ searchText: '' })
            }
        },
        render: text =>
            this.state.searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                    searchWords={[this.state.searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    })

    handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm()
        this.setState({
            searchText: selectedKeys[0],
            searchedColumn: dataIndex,
        })
    }

    handleReset = (clearFilters, confirm) => {
        clearFilters()
        confirm({ closeDropdown: true })
        this.setState({ searchText: '' })
    }

    handleVisible = (proid) => {
        this.setState({
            shopDetailVisible: true
        })
        requestShopDetail(proid).then(res => {
            this.setState({
                shopDetail: res.data || { category: '', brand: '' },
                loadingDetail: false
            })
        })
    }

    copyWhenClick (text, tip = '复制商品id成功！') {
        console.log(text,tip)
        const copyer = document.getElementById('copy')
        copyer.value = text
        copyer.select()
        document.execCommand('copy')
        message.success(tip)
    }

    onCancel = () => {
        this.setState({
            shopDetailVisible: false,
            loadingDetail: true
        })
    }

    sendProduct = (orderid) => {
        requestModifiedOrderToSend(orderid).then(res => {
            console.log(res.data)
            this.init()
        })
    }

    noProduct = (orderid) => {
        requestModifiedNoStoreOrder(orderid).then(res => {
            console.log(res.data)
            this.init()
        })
    }

    element (columns) {
        let element = null
        if (this.state.loading) {
            element = (<div className="loading">
                <Spin tip="Loading..." spinning={this.state.loading} size="large"/>
            </div>)
        } else {
            element = (<>
                <Table columns={columns} dataSource={this.state.dataSource}
                       scroll={{ x: 1000, y: this.state.tableHeight }} rowKey={record => record.orderid}/>
                <Modal width={1000} footer={null} visible={this.state.shopDetailVisible}
                       onCancel={this.onCancel.bind(this)}>
                    {this.state.loadingDetail ? (
                        <div className="loading" style={{ display: 'flex', justifyContent: 'center' }}>
                            <Spin tip="获取中..." spinning={this.state.loadingDetail} size="large"/>
                        </div>) : (<Descriptions title="商品详情" bordered>
                        {/*eslint-disable-next-line*/}
                        <Descriptions.Item label="商品名称"><a title="点击复制id"
                                                           onClick={this.copyWhenClick.bind(this, this.state.shopDetail.proid,"复制商品id成功")}>{this.state.shopDetail.proname}</a></Descriptions.Item>
                        <Descriptions.Item label="品牌">{this.state.shopDetail.brand}</Descriptions.Item>
                        <Descriptions.Item label="分类">{this.state.shopDetail.category}</Descriptions.Item>
                        <Descriptions.Item label="商品原价">{this.state.shopDetail.originprice}</Descriptions.Item>
                        <Descriptions.Item label="商品折扣" span={2}>
                            {this.state.shopDetail.discount}
                        </Descriptions.Item>
                        <Descriptions.Item label="商品状态" span={1}>
                            <Badge status="processing" text={this.state.shopDetail.issale ? '上架中' : '已下架'}/>
                        </Descriptions.Item>
                        <Descriptions.Item label="商品库存" span={2}>{this.state.shopDetail.stock}</Descriptions.Item>
                        <Descriptions.Item label="上架时间" span={1}>{this.state.shopDetail.time}</Descriptions.Item>
                        <Descriptions.Item label="商品销量" span={2}>{this.state.shopDetail.sales}</Descriptions.Item>
                    </Descriptions>)}
                </Modal>
            </>)
        }
        return element
    }

    render () {
        const columns = [
            {
                title: '订单号',
                dataIndex: 'orderid',
                key: 'orderid',
                width: 250,
                fixed: 'left',
                ...this.getColumnSearchProps('orderid', '请输入订单号'),
                render: (text) => text
            },
            {
                title: '商品名',
                width: 240,
                dataIndex: 'proname',
                key: 'proname',
                ...this.getColumnSearchProps('proname', '请输入id或商品名', 'proid'),
                // eslint-disable-next-line
                render: (text, record) => <a onClick={this.handleVisible.bind(this, record.proid)}>{text}</a>,
            },
            {
                title: '商品图片',
                width: 150,
                dataIndex: 'img1',
                key: 'img1',
                render: (value) => <Image key="img" src={value} width={100} height={100} placeholder={
                    <Image
                        preview={false}
                        src="https://web.chengqige.com/vipshop/v1/dist/static/loading.gif"
                        width={100}
                        height={100}
                    />
                }/>
            },
            {
                title: '订单价格',
                width: 150,
                dataIndex: 'originprice',
                key: 'originprice',
                render: (text, record) => (<label>{Math.floor(record.originprice * record.discount*record.count/10)}</label>)
            },
            {
                title: '商品规格',
                width: 150,
                dataIndex: 'size',
                key: 'size',
                render: (text) => (<Tag color="green">{text}</Tag>)
            },
            {
                title: '购买数量',
                width: 150,
                dataIndex: 'count',
                key: 'count',
            },
            {
                title: '客户姓名',
                width: 130,
                dataIndex: 'name',
                ...this.getColumnSearchProps('name', '请输入userid或姓名', 'userid'),
                // eslint-disable-next-line
                render: (text,record) => <a onClick={this.copyWhenClick.bind(this,record.userid,'复制userid成功')}>{text}</a>,
                key: 'name',
            },
            {
                title: '客户电话',
                width: 130,
                dataIndex: 'tel',
                key: 'tel'
            },
            {
                title: '送货省',
                width: 100,
                dataIndex: 'province',
                ...this.getColumnSearchProps('province', '请输入省'),
                render: (text) => text,
                key: 'province'
            },
            {
                title: '送货城市',
                width: 120,
                dataIndex: 'city',
                ...this.getColumnSearchProps('city', '请输入城市'),
                render: (text) => text,
                key: 'city'
            },
            {
                title: '送货区',
                width: 100,
                ...this.getColumnSearchProps('county', '请输入区'),
                render: (text) => text,
                dataIndex: 'county'
            },
            {
                title: '详细地址',
                width: 350,
                dataIndex: 'addressDetail',
                ...this.getColumnSearchProps('addressDetail', '请输入部分详细地址'),
                render: (text) => text,
                key: 'addressDetail'
            },
            {
                title: '操作',
                width: 180,
                fixed: 'right',
                render: (text, record) => (
                    <Space size="middle">
                        <Popconfirm onConfirm={this.sendProduct.bind(this, record.orderid)} title="确认发货？">
                            <Button>
                                发货
                            </Button>
                        </Popconfirm>
                        {/*<Popconfirm onConfirm={this.noProduct.bind(this, record.orderid)} title="确认无货？">*/}
                        {/*    <Button type="primary" danger>*/}
                        {/*        缺货*/}
                        {/*    </Button>*/}
                        {/*</Popconfirm>*/}
                    </Space>
                ),
            },
        ]

        return (<QueueAnim className="demo-content" key="demo">
            {this.props.show ? <div className="demo-tbody" key="a">{this.element(columns)}</div> : null}
        </QueueAnim>)
    }
}

export default connect((state) => {
    return {
        show: state.getIn(['fade', 'show'])
    }
})(Order)
